<template>
    <div>
        <Form :label-width="120" :model="dataToQuery">
            <div v-if="switchFlag">
                <Row :gutter="16" class="query-form2">
                    <i-col span="8">
                        <FormItem label="创建人：">
                            <Input v-model="dataToQuery.userName" placeholder="请输入创建人"/>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="企业名称：">
                            <Input v-model="dataToQuery.companyName" placeholder="请输入企业名称"/>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="所属地：" >
                            <Input v-model="dataToQuery.locationName" placeholder="请输入所属地（支持模糊查询）"/>
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16" class="query-form2">
                    <i-col span="8">
                        <FormItem label="消防重点单位：">
                            <Select v-model="dataToQuery.ifEmphasis">
                                <Option v-for="item in ifEmphasisList " :value="item.lable"> {{item.lable}} </Option>
                            </Select>
                        </FormItem>
                    </i-col>
                    <i-col span="16">
                        <div style="float: right;">
                            <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
                            <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2" type="text" >收起<Icon type="ios-arrow-up" /></Button>
                        </div>
                    </i-col>
                </Row>
            </div>
            <div v-else>
                <Row :gutter="16" class="query-form2" >
                    <i-col span="8">
                        <FormItem label="创建人：">
                            <Input v-model="dataToQuery.userName" placeholder="请输入创建人"/>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="企业名称：">
                            <Input v-model="dataToQuery.companyName" placeholder="请输入企业名称"/>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <div style="float: right;">
                            <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
                            <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text" >展开<Icon type="ios-arrow-down"/></Button>
                        </div>
                    </i-col>
                </Row>
            </div>
        </Form>
        <Row type="flex" justify="start" class="query-form">
            <i-col>
                <Button icon="md-add" class="ivu-btn-add" @click="addInfo">新增</Button>
            </i-col>
            <i-col>
                <Button icon="md-cloud-download" class="ivu-btn-add" @click="exportAllList">导出</Button>
            </i-col>
        </Row>
        <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据!" @on-selection-change = 'getSelectRows' :loading='pageStatus.loading'
               border :columns="columns1"  :data="dataTable" >
        </Table>
        <Row type="flex" justify="end" >
            <i-col span="24">
                <Page :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </i-col>
        </Row>
        <Modal  title="消防重点设备设施" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow" :width=800 :styles="{height:modalHeight}" class-name='limit-height-dialog'>
            <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':'modal-form'"
                  :show-message="false" :model="dataToView" :rules="mode === 'view'?{} :ruleCustom"
                  :label-position="mode === 'view'?'right':'top'" :label-width="mode === 'view'?170:null">
                <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
                    <i-col span="12">
                        <FormItem label='单位名称：' prop='companyName'>
                            <div v-if="mode === 'view'">{{ dataToView.companyName }}</div>
                            <orgDom ref="orgDom" @setOrgInfo="setOrgName" :orgInfo="{name: dataToView.companyName}" :rootOrgId="rootOrgId" v-else></orgDom>
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label='所属二级集团：'>
                            <div v-if="mode === 'view'">{{ dataToView.twoLevelGroupName }}</div>
                            <Input v-else v-model='dataToView.twoLevelGroupName'></Input>
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
                    <i-col span="12">
                        <FormItem label='所在地：'  prop="ifEmphasis">
                            <div v-if="mode === 'view'">{{areaCodeToAreaName(dataToView.location)}}</div>
                            <Cascader v-else :data="tempAreaTree" v-model="dataToView.locationName" change-on-select :transfer="true"
                                      :load-data="areaTreeLoadData" :render-format="labels=>labels.join('·')"  :clearable='false'
                                      @on-change="(value,selectedData)=>{$set(dataToView,'location',value.join(','))}"></Cascader>
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label='是否消防重点单位：' prop="ifEmphasis">
                            <div v-if="mode === 'view'">{{ dataToView.ifEmphasis }}</div>
                            <Select v-else v-model="dataToView.ifEmphasis">
                                <Option v-for="item in ifEmphasisList " :value="item.lable"> {{item.lable}} </Option>
                            </Select>
                        </FormItem>
                    </i-col>
                </Row>
                <Row type="flex" justify="start">
                    <i-col>
                        <Button icon="md-add" class="ivu-btn-add" @click="addPartInfo" v-if="mode != 'view'">新增设施</Button>
                    </i-col>
                </Row>
                <Table ref='table2' height="300"  no-data-text="没有查询到相关数据!"  border :columns="columns2"  :data="dataTable2" ></Table>

            </Form>
            <div slot="footer">
                <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-save' @click="submit('dialogForm')" >确定</Button>
                <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
                <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
            </div>
        </Modal>
        <Modal title="消防重点设备设施" :transfer=false :mask-closable="false" v-model="modal2" :styles="{height:'520px'}" :width=700>
            <Form ref="dialogForm2" :model="formData" :rules="ruleCustom2" label-position="top">
                <Row :gutter="16" >
                    <i-col span="12">
                        <FormItem label="设备名称：">
                            <Input v-model="formData.deviceName" placeholder="请输入设备名称"/>
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="所在位置：">
                            <Input v-model="formData.positionName" placeholder="请输入所在位置"></Input>
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16" >
                    <i-col span="12">
                        <FormItem label="规格型号：">
                            <Input v-model="formData.specifications" placeholder="请输入规格型号"/>
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="数量：">
                            <InputNumber style="width:100%" v-model="formData.quantity" ></InputNumber>
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16" >
                    <i-col span="12">
                        <FormItem label="责任人：">
                            <userDom ref="userDom" :ifUser=true  :singleChoice=true @setData="setUserInfo" :rootOrgName="rootOrgName" :selectData="{name: formData.responsibilityUserName}"></userDom>
                        </FormItem>
                    </i-col>
                    <i-col span="12">
                        <FormItem label="责任部门：">
                            <Input v-model="formData.responsibilityOrgName" placeholder="请选择责任人" readonly/>
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16">
                    <i-col span="24">
                        <FormItem label="备注：">
                            <Input v-model="formData.remark" placeholder="请输入备注" type="textarea"/>
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div slot="footer">
                <Button @click="savePartInfo" class="ivu-btn-save">确定</Button>
                <Button @click="modal2 = false" class="ivu-btn-cancel" >取消</Button>
            </div>
        </Modal>
        <div v-show="downloading"
             style="position:absolute;top:0;left:0;width:100%;height:100%;z-index:99999;background-color:#000000;opacity:0.5;">
            <svg-bar style="position:absolute;top:50%;left:50%;margin-left:-100px;margin-top:-100px"
                     :options="options" :value="batchProcess"></svg-bar>
        </div>
    </div>
</template>

<script>

    import {formatDate, verifyIdCard, createFormAndSubmit} from '@/tools/index'
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    import {sessionStorage} from '@/common/cacheUtils.js';
    import {Api} from '@/api/index.js'
    import svgBar from 'svg-progress-bar'
    import orgDom from "@/components/input-org.vue";
    import {mapState} from 'vuex'
    import userDom from "@/components/input-user.vue";

    export default {
        name: "curcialFireControlFacilitiesList",
        components:{
            svgBar,
            orgDom,
            userDom
        },
        data(){
            return{
                ...this.createCommonDataField(),
                modalHeight: '',
                modal2: false,
                switchFlag: false,
                tableHeight:10,
                columns1: [
                    { title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRender},
                    { key:'companyName',title: '企业名称',  align: 'center', minWidth: 180},
                    { key:'twoLevelGroupName',title: '所属二级集团',  align: 'center', minWidth: 200},
                    { key:'location',title: '所属地',  align: 'center', minWidth: 200, render: (h, params) =>{ return h('span', this.areaCodeToAreaName(params.row.location));} },
                    { key:'ifEmphasis',title: '是否消防重点单位',  align: 'center', minWidth: 170},
                    { key:'userName',title: '填报人',  align: 'center', minWidth: 200},
                    { key:'createUserPhone',title: '填报人电话',  align: 'center', minWidth: 200},
                    { key:'createDate',title: '填报时间',  align: 'center', minWidth: 200, render: this.renderCellDate},
                    this.getActionColumns(),
                ],
                ruleCustom: {
                    companyName: [{required: true, message: '请填写自评问题整改情况', trigger: 'blur, change'}],
                    twoLevelGroupName: [{required: true, message: '所属二级集团', trigger: 'blur, change'}],
                    location: [{required: true, message: '所属地', trigger: 'blur, change'}],
                    ifEmphasis: [{required: true, message: '是否消防重点单位', trigger: 'blur, change'}],
                },
                queryUrl: Api.queryCurcialFireControlFacilities,
                updateUrl:Api.updateCurcialFireControlFacilities,
                saveUrl:Api.saveCurcialFireControlFacilities,
                deleteUrl: Api.deleteCurcialFireControlFacilities,
                downloading: false,
                batchProcess: 0,
                rootOrgId: sessionStorage('userId').getObject('userId').companyId,
                rootOrgName: sessionStorage('userId').getObject('userId').companyName,
                ifEmphasisList: [{lable: '是'}, {lable: '否'}],
                columns2: [
                    { title: '序号', width: 80, align: 'center', type: 'index'},
                    { key:'deviceName',title: '设备名称',  align: 'center', minWidth: 180},
                    { key:'positionName',title: '所在位置',  align: 'center', minWidth: 200},
                    { key:'specifications',title: '规格型号',  align: 'center', minWidth: 200},
                    { key:'quantity',title: '数量',  align: 'center', minWidth: 200},
                    { key:'responsibilityUserName',title: '责任人',  align: 'center', minWidth: 200},
                    { key:'responsibilityOrgName',title: '责任部门',  align: 'center', minWidth: 200},
                    { key:'remark',title: '备注',  align: 'center', minWidth: 200},
                ],
                dataTable2: [],
                ruleCustom2: [

                ],
                formData: {},
                addItem: false,
                index: 0
            }
        },
        watch: {
            "dialogShow":function(qw,er){
                if(!qw){
                    this.columns2.splice(this.columns2.length-1, 1);
                    this.dataTable2 = [];
                }
            },
            "modal2": function (qw, er) {
                if(!qw){
                    setTimeout(() => {
                        this.$refs.userDom.resetCurrentUser();
                    }, 300);
                }
            }
        },
        computed: {
            options: function() {
                return {
                    radius: 50,//大小
                    duration: 2,//变化时间长度
                    circleWidth: 5,//圆环宽度
                    pathColors: ['#A2A2A2', '#FA5657'], //圆环 底色和 上面的颜色
                    circleLineCap: 'round',//进度条 形状  圆环 或者矩形
                    text: function (value) {
                        return this.htmlifyNumber(value) + '<span style="font-size: 0.4em;">%</span>';
                    },
                    textColor: 'rgb(33, 150, 243)'
                }
            },
            ...mapState('trhg', {
                areaMap: state => state.area.areaMap?state.area.areaMap:[],
                areaTreeMap: state => state.area.areaTreeMap?state.area.areaTreeMap:{},
            }),
        },
        async mounted() {
            this.setTableHeight();
            await this.$store.dispatch('trhg/area/query', {scope:this}, { root: true });
            this.query();
            this.tempAreaTree = this.areaTreeMap['0']
        },
        methods: {
            ...pageCommonFunction,
            query() {
                this.dataToQuery.createOrgId = sessionStorage('userId').getObject('userId').companyId;
                this.queryAjax();
            },
            addInfo() {
                this.mode = 'add'
                this.dialogShow = true;
                this.modalHeight = '650px';
                this.dataToView = {
                    id: this.get_uuid(),
                    curcialFireFacilitiesList: [],
                    createUserPhone: sessionStorage('userId').getObject('userId').mobileNumber
                }
                this.addColums('add');
            },
            createEmptyDataToAdd() {
                return {
                    orgId: sessionStorage('userId').getObject('userId').companyId,
                    id: this.get_uuid(),
                    idFiles: [],
                }
            },
            async beforeEditDialogOpen(data) {
                setTimeout(() => {
                    this.$refs.orgDom.setCurrentOrg();
                }, 300);
                this.modalHeight = '650px';
                if(data.row.location){
                    data.row.locationName = data.row.location.split(',');
                    data.row.companyAddressName = this.areaCodeToAreaName(data.row.location)
                }
                this.dataTable2 = data.row.curcialFireFacilitiesList;
                this.addColums('edit');
            },
            async afterDataToViewInit(data) {
                if (data && data.location) {
                    let companyAddressArr = data.location.split(',')
                    this.tempAreaTree = []
                    setTimeout(() => {
                        this.tempAreaTree = this.addressEditArr(this.areaTreeMap,companyAddressArr)
                    }, 100)
                }
            },
            beforeViewDialogOpen(data){
                this.modalHeight = '550px';
                this.dataTable2 = data.row.curcialFireFacilitiesList;
            },
            submit(name) {
                let att = this.areaCodeToAreaName(this.dataToView.location);
                this.dataToView.locationName = att;
                this.dataToView.curcialFireFacilitiesList = this.dataTable2;
                this.submitAjax(name);
            },
            deleteData(params) {
                this.deleteDateAjax(params);
            },
            addPartInfo(){
                this.modal2 = true;
                this.addItem = false;
                this.formData = {
                    id: this.get_uuid(),
                    controlFacilitiesId: this.dataToView.id
                }
            },
            savePartInfo(){
                console.log(this.formData)

                if(this.addItem){
                    let index = this.index;
                    setTimeout(()=>{
                        this.dataTable2[index] = this.formData;
                        },1000)
                }else{
                    this.dataTable2.push(this.formData);
                }
                this.modal2 = false;
            },
            setOrgName(data) {
                this.$set(this.dataToView, 'companyId', data.orgId);
                this.$set(this.dataToView, 'companyName', data.orgName);
                this.queryTwolevelOrg(data.orgId);
            },
            queryTwolevelOrg(orgId) {
                this.$http.get(Api.securityDirectorInfo + '/twoLevelOrg', {params: {companyId: orgId}}).then((res) => {
                    if (res.data.status == 200) {
                        if (res.data.data != null) {
                            this.$set(this.dataToView, 'twoLevelGroupId', res.data.data.orgId);
                            this.$set(this.dataToView, 'twoLevelGroupName', res.data.data.orgName);
                        }
                    }
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            setUserInfo(data){
                this.$set(this.formData, 'responsibilityUserId', data.userId);
                this.$set(this.formData, 'responsibilityUserName', data.userName);
                this.$set(this.formData, 'responsibilityOrgId', data.orgId);
                this.$set(this.formData, 'responsibilityOrgName', data.orgInfo.orgName);
            },
            addColums(mode){
                if(mode == 'edit' || mode == 'add')
                    this.columns2.push({
                        key:'remark',title: '操作',  align: 'center', minWidth: 120,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.modal2 = true;
                                            this.formData = params.row;
                                            this.addItem = true;
                                            this.index = params.index;
                                            setTimeout(() => {
                                                this.$refs.userDom.setCurrentInfo();
                                            }, 300);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: 'red',
                                    },
                                    on: {
                                        click: () => {
                                            this.$Modal.confirm({
                                                title: '数据删除',
                                                content: '<p>确定删除该条信息</p>',
                                                okText: '确认',
                                                onOk: () => {
                                                    this.dataTable2.splice(params.index,1);
                                                },
                                                cancelText: '取消'
                                            });
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    });
            },
            exportAllList(){
                let data = {
                    createOrgId: sessionStorage('userId').getObject('userId').companyId
                };
                let _this = this;
                this.downloading = true;
                data = Object.assign(data,JSON.parse(JSON.stringify(this.dataToQuery)));
                this.$http.get(Api.exportCurcialFireControlFacilities,{
                    params: data,
                    responseType: 'blob',
                    progress:function(e){
                        _this.batchProcess = 100 * (e.loaded / e.total);
                        if(_this.batchProcess == 100){
                            _this.downloading = false;
                        }
                    }
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: "application/vnd.ms-excel"
                    })
                    aLink.href = URL.createObjectURL(blob);
                    aLink.download = "消防重点设施台账("+ formatDate(new Date(), "yyyy-MM-dd")+ ").xlsx" //标题
                    aLink.click();
                    document.body.appendChild(aLink);
                    this.downloading = false;
                }, function(res){
                    this.$Message.error('生成失败');
                    this.downloading = false;
                })
            }
        }
    }
</script>

<style scoped>

</style>